package com.lagou.edu.service.impl;

import com.lagou.edu.dao.IAuthCodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.AuthCodeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
public class AuthCodeServiceImpl implements AuthCodeService {


    @Autowired
    private IAuthCodeDao iAuthCodeDao;


    @SuppressWarnings("all")
    @Override
    public boolean saveAuthCode(String email,String code) {
        Date date = new Date();
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);

        // 不过期不给，过期重来
        LagouAuthCode authCodeFromDao = getAuthCodeFromDao(lagouAuthCode);
        if (authCodeFromDao != null) {
            if (authCodeFromDao.getExpiretime().getTime() > System.currentTimeMillis()) {
                return false;
            }
        }

        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(date);
        lagouAuthCode.setExpiretime(new Date(date.getTime() + TimeUnit.MINUTES.toMillis(10)));
        LagouAuthCode save = iAuthCodeDao.save(lagouAuthCode);
        return save!=null;
    }

    @Override
    public LagouAuthCode getAuthCode(String email,String code) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        return getAuthCodeFromDao(lagouAuthCode);
    }

    public LagouAuthCode getAuthCodeFromDao(LagouAuthCode lagouAuthCode) {
        Example<LagouAuthCode> example = Example.of(lagouAuthCode);
        Optional<LagouAuthCode> one = iAuthCodeDao.findOne(example);
        return one.orElse(null);
    }

    public Integer validate(String email, String code){
        LagouAuthCode authCode = getAuthCode(email, code);
        //错误
        if(authCode == null || !authCode.getCode().equals(code)){
            return 1;
        }else if( new Date().after(authCode.getExpiretime())){
            return 2;
        }
        return 0;
    }
}
